package com.cw.windows.action;

import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;

import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;

import com.cw.action.LotteryAction;
import com.cw.gui.MainPanel;

public class CascadeAction extends LotteryAction {

	public CascadeAction(String name, String icon, MainPanel t) {
		super(t, name, icon);
	}

	/**
	 * Invoked when an action occurs.
	 * 
	 * @param e
	 *            ActionEvent
	 * @todo Implement this java.awt.event.ActionListener method
	 */
	public void actionPerformed(ActionEvent e) {
		cascade(mPanel.getDeskTop());
	}

	public void cascade(JDesktopPane desktopPane) {
		JInternalFrame[] frames = desktopPane.getAllFrames();
		if (frames.length == 0) {
			return;
		}

		cascade(frames, desktopPane.getBounds());
	}

	public void cascade(JDesktopPane desktopPane, int layer) {
		JInternalFrame[] frames = desktopPane.getAllFramesInLayer(layer);
		if (frames.length == 0) {
			return;
		}

		cascade(frames, desktopPane.getBounds());
	}

	private void cascade(JInternalFrame[] frames, Rectangle dBounds) {
		int margin = 0;

		Insets ins = null;
		Dimension d, cd;
		for (int i = 0; i < frames.length; i++) {
			d = frames[i].getSize();
			cd = frames[i].getContentPane().getSize();
			margin += Math.max(d.width - cd.width, d.height - cd.height);
		}

		int width = dBounds.width - margin;
		int height = dBounds.height - margin;
		int offset = 0;
		for (int i = 0; i < frames.length; i++) {
			frames[i].setBounds(dBounds.x + offset, dBounds.y + offset, width,
					height);
			d = frames[i].getSize();
			cd = frames[i].getContentPane().getSize();
			frames[i].toFront();
			offset += Math.max(d.width - cd.width, d.height - cd.height);
		}
	}
}
